﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Windows;
using LEShortcut.Dialogs.Xaml;
using LEShortcut.Helper;
using LEShortcut.Models;
using Microsoft.Win32;

namespace LEShortcut
{
    /// <summary>
    ///     Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private readonly AppCache _cache = new AppCache();
        private readonly string _conf = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config.js");
        private AppConfig _config;
        private Dictionary<int, string> _cultures = new Dictionary<int, string>();

        private void App_OnStartup(object sender, StartupEventArgs e)
        {
            InitCultureResource();
            InitConfig();
            UpdateCultureResource();
            Current.Resources["cache"] = _cache;
        }

        private void InitCultureResource()
        {
            _cultures = new Dictionary<int, string>();
            I18NHelper.GetGlobalResourcesDictionary(_cultures, "i18n");
            _cache.Cultures = _cultures;
            if (I18NHelper.LoadCultureResouce(_cultures, new CultureInfo("en-us").LCID, CultureInfo.CurrentCulture.LCID))
                _cache.CurrentCulture = CultureInfo.CurrentCulture.LCID;
        }

        private void UpdateCultureResource()
        {
            if (string.IsNullOrWhiteSpace(_config.Language)) return;
            int lcid = new CultureInfo(_config.Language).LCID;
            if (CultureInfo.CurrentCulture.LCID == lcid) return;
            if (I18NHelper.LoadCultureResouce(_cultures, CultureInfo.CurrentCulture.LCID, lcid))
                _cache.CurrentCulture = CultureInfo.CurrentCulture.LCID;
        }

        private void InitConfig()
        {
            if (!File.Exists(_conf)) InitNewConfig();
            else
            {
                bool sr = ConfigHelper.LoadConfig(ref _config, _conf);
                //Prenvent unexcepted change on config file
                if (!sr) InitNewConfig();
            }
            if (string.IsNullOrWhiteSpace(_config.LePath) || !Directory.Exists(_config.LePath)) UpdateLePath();
            _cache.Config = _config;
        }

        private void InitNewConfig()
        {
            _config = new AppConfig();
            _config.LastLaunched = DateTime.SpecifyKind(_config.LastLaunched, DateTimeKind.Utc);
            bool sr = ConfigHelper.SaveConfig(_config, _conf);
            if (!sr)
            {
                new SaveConfigFailedDialog().ShowDialog();
                Current.Shutdown();
            }
        }

        private void UpdateLePath()
        {
            var openDialog = new OpenFileDialog
            {
                Title = "ChooseLeLocationTitle".GetI18NString(),
                FileName = "LEProc",
                AddExtension = true,
                Filter = "ChooseLeLocationFilter".GetI18NString(),
            };
            bool? or = openDialog.ShowDialog();
            if (or != null && (bool) or)
            {
                string p = Path.GetDirectoryName(openDialog.FileName);
                if (p != null && File.Exists(Path.Combine(p, "LEConfig.xml")))
                {
                    _config.LePath = p;
                    if (ConfigHelper.SaveConfig(_config, _conf)) return;
                    new SaveConfigFailedDialog().ShowDialog();
                    Current.Shutdown();
                }
                else
                {
                    new NoLeDirDialog().ShowDialog();
                }
            }
            else Current.Shutdown();
        }
    }
}